package elephant.rpc.threadpool;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 
 * @author skydu
 *
 */
public class RPCThreadFactory implements ThreadFactory {
	//
	private static Logger logger=LoggerFactory.getLogger(RPCThreadFactory.class);
	//
	private AtomicInteger threadCounter=new AtomicInteger();
	private String name;
	private ClassLoader contextClassLoader;
	//
	public RPCThreadFactory(String name,ClassLoader contextClassLoader) {
		this.name=name;
		this.contextClassLoader=contextClassLoader;
	}
	@Override
	public Thread newThread(Runnable r) {
		Thread t=new Thread(r);
		t.setName(name+"-"+threadCounter.incrementAndGet());
		if(contextClassLoader!=null){
			t.setContextClassLoader(contextClassLoader);
		}
		Thread.UncaughtExceptionHandler logHander=new Thread.UncaughtExceptionHandler() {
			@Override
			public void uncaughtException(Thread t, Throwable e) {
				logger.error(e.getMessage(),e);
			}
		};
		t.setUncaughtExceptionHandler(logHander);
		return t;
	}
	//
	/**
	 * @return the contextClassLoader
	 */
	public ClassLoader getContextClassLoader() {
		return contextClassLoader;
	}
	/**
	 * @param contextClassLoader the contextClassLoader to set
	 */
	public void setContextClassLoader(ClassLoader contextClassLoader) {
		this.contextClassLoader = contextClassLoader;
	}
}
